package com.demo.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;

/**
 * @author wangning
 * @date 2023/10/31 11:49
 */
public class UdpServer {
    // 创建一个Socket 对象
    DatagramSocket socket = null;

    // 给服务器指定一个端口号
    public UdpServer(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器已启动!");
        while (true) {
            // 1. 接收来自客户端的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(requestPacket);
            // 将请求转变为String类型能够更方便的去处理.
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            // 2. 处理请求
            String response = process(request);
            // 3. 将请求打包成一个数据报
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress()); // 这里要指定客户端的IP地址和端口号
            // 4. 发送给客户端
            socket.send(responsePacket);
            System.out.printf("[%s : %d] 请求:  %s 响应 : %s \n", requestPacket.getAddress(), requestPacket.getPort(), request, response);
        }
    }

    private String process(String request) {
        HashMap<String, String> hash = new HashMap<>();
        hash.put("one", "1");
        hash.put("two", "2");
        hash.put("three", "3");
        hash.put("four", "4");
        return hash.getOrDefault(request, "null");
    }

    public static void main(String[] args) throws IOException {
        // 给服务器指定一个9090的端口号.
        UdpServer udpTraServer = new UdpServer(9090);
        udpTraServer.start();
    }

}
